import OSS from 'ali-oss';
import Compressor from 'compressorjs';
import { randomString } from '@/utils/index.js';

const { accessKeyId, accessKeySecret, region, endpoint } = {
  region: 'oss-cn-hangzhou',
  accessKeyId: 'LTAI5tFCvUZKLX5g1Ebd5Cp6',
  accessKeySecret: 'hjvSnAxM9ZLvVK00YeG02tIJyrUn73',
  endpoint: 'oss-cn-hangzhou.aliyuncs.com'
};

const client = new OSS({
  // yourRegion填写Bucket所在地域。以华东1（杭州）为例，Region填写为oss-cn-hangzhou。
  region: region,
  // 从STS服务获取的临时访问密钥（AccessKey ID和AccessKey Secret）。
  accessKeyId: accessKeyId,
  accessKeySecret: accessKeySecret,
  endpoint: endpoint,
  // 填写Bucket名称。
  bucket: 'mdhw'
});
/**
 * 图片压缩
 */
function compressImage(fileList, backType, limitSize, quality) {
  const promiseAry = [];
  const maxSize = limitSize * 1024 * 1024;
  fileList.forEach(image => {
    promiseAry.push(new Promise((resolve, reject) => {
      if (image.size <= maxSize) { // 没操过限制，不用压缩
        resolve(image)
      }
      else {
        new Compressor(image, {
          // maxWidth: 750,
          // maxHeight: 750,
          quality: quality || 0.8,
          success(result) {
            let file = new File([result], image.name, { type: image.type })

            if (!backType || backType == 'blob') {
              resolve(result)
            } else if (backType == 'file') {
              resolve(file)
            } else {
              resolve(file)
            }
          },
          error(err) {
            console.log('图片压缩失败---->>>>>', err)
            resolve(image)
          }
        })
      }
    }))
  })
  return Promise.all(promiseAry)
}

const defaultLimit = 1;
/**
 *
 * @param fileList 上传图片的资源路径
 * @param dir oss要保存的文件夹
 * @param limitSize oss图片限制 默认1m 0为不限制
 * @returns {OSS文件路径}
 */

async function uploadOSS(fileList, dir = 'file', {
  limitSize = defaultLimit, compress = false
}) {
  return new Promise((resolve, reject) => {
    const promiseAry = [];
    let randomVal, randomStr, imgtype, fileName, tmpAry, maxSize = limitSize * 1024 * 1024;
    let _Promise = compress ? compressImage(fileList, 'file', limitSize) : Promise.resolve(fileList)

    if (compress) {
      console.log('压缩前的图片列表', fileList)
    }
    _Promise.then(fileList => {
      if (compress) {
        console.log('压缩后的图片列表', fileList)
      }
      const canUploadList = limitSize == 0 ? fileList : fileList.filter(file => file.size <= maxSize);
      canUploadList.forEach(file => {

        tmpAry = file.name.split('.');
        imgtype = tmpAry[tmpAry.length - 1]
        randomVal = +new Date();
        randomStr = randomString()
        fileName = `${randomVal}_${randomStr}.${imgtype}`
        promiseAry.push(client.put(`${dir}/${fileName}`, file, {
          headers: {
            'aa': 'aa'
          }
        }))
      })
      Promise.all(promiseAry).then(result => {
        let code = canUploadList.length == fileList.length ? 1 : 0
        resolve({
          result,
          code,
          msg: code == 1 ? '上传成功' : `${fileList.length == 1 ? '' : '部分'}图片大小超过${limitSize}M`
        });
      }).catch(e => {
        reject(e)
      })
    })

  });
}

export { uploadOSS, defaultLimit }